package com.cyd.demo.service;

import com.cyd.demo.entity.SexEnum;
import com.cyd.demo.entity.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.util.List;

/**
 * @Name : com.cyd.demo.service.JdbcTemplateServiceImpl
 * @Description : 描述
 * Created by cyd on 2021-05-25 17:18:16
 */
@Service
public class JdbcTemplateServiceImpl implements JdbcTemplateService {

    @Resource
    JdbcTemplate template;

    private RowMapper<User> getUserMapper() {
        RowMapper<User> rowMapper = (ResultSet rs, int rownum) -> {
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setName(rs.getString("user_name"));
            user.setSex(SexEnum.getInstance(rs.getInt("sex")));
            user.setNote(rs.getString("note"));
            return user;
        };
        return rowMapper;
    }

    @Override
    public User getUser(Long id) {
        String sql = "select * from t_user where id = ?";
        Object[] params = new Object[]{id};
        User user = template.queryForObject(sql, params, getUserMapper());
        return user;
    }

    @Override
    public List<User> findUsers(String userName) {
        return null;
    }

    @Override
    public int insertUser(User user) {
        String sql = "insert into t_user set user_name=?,sex=?,note=? where id=?";
        return template.update(sql, user.getName(), user.getSex().getName(), user.getNote());
    }
}
